import { NextResponse } from 'next/server';
import { pool } from '@/lib/db';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

// GET /api/schedules - Get all schedules
export async function GET() {
  try {
    const [schedules] = await pool.query<RowDataPacket[]>('SELECT * FROM schedules');
    return NextResponse.json(schedules);
  } catch (error) {
    console.error('Error fetching schedules:', error);
    return NextResponse.json(
      { error: 'Failed to fetch schedules' },
      { status: 500 }
    );
  }
}

// POST /api/schedules - Create a new schedule
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { device_id, start_time, end_time, days, is_active = true } = body;

    if (!device_id || !start_time || !end_time || !days) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    const [result] = await pool.query<ResultSetHeader>(
      'INSERT INTO schedules (device_id, start_time, end_time, days, is_active) VALUES (?, ?, ?, ?, ?)',
      [device_id, start_time, end_time, days, is_active]
    );

    const [newSchedule] = await pool.query<RowDataPacket[]>(
      'SELECT * FROM schedules WHERE id = ?',
      [result.insertId]
    );

    return NextResponse.json(newSchedule[0], { status: 201 });
  } catch (error) {
    console.error('Error creating schedule:', error);
    return NextResponse.json(
      { error: 'Failed to create schedule' },
      { status: 500 }
    );
  }
}

// PUT /api/schedules/{id} - Update schedule
export async function PUT(request: Request, { params }: { params: { id: string } }) {
  try {
    const [existing] = await pool.query<RowDataPacket[]>(
      'SELECT * FROM schedules WHERE id = ?',
      [params.id]
    );
    
    if (!existing[0]) {
      return NextResponse.json({ error: 'Schedule not found' }, { status: 404 });
    }

    const body = await request.json();
    const { device_id, start_time, end_time, days, is_active } = body;

    await pool.query(
      'UPDATE schedules SET device_id = ?, start_time = ?, end_time = ?, days = ?, is_active = ? WHERE id = ?',
      [device_id, start_time, end_time, days, is_active, params.id]
    );

    const [updated] = await pool.query<RowDataPacket[]>(
      'SELECT * FROM schedules WHERE id = ?',
      [params.id]
    );
    
    return NextResponse.json(updated[0]);
  } catch (error) {
    console.error('Error updating schedule:', error);
    return NextResponse.json(
      { error: 'Failed to update schedule' },
      { status: 500 }
    );
  }
}

// DELETE /api/schedules/{id} - Delete schedule
export async function DELETE(request: Request, { params }: { params: { id: string } }) {
  try {
    const [existing] = await pool.query<RowDataPacket[]>(
      'SELECT * FROM schedules WHERE id = ?',
      [params.id]
    );
    
    if (!existing[0]) {
      return NextResponse.json({ error: 'Schedule not found' }, { status: 404 });
    }

    await pool.query('DELETE FROM schedules WHERE id = ?', [params.id]);
    
    return NextResponse.json(
      { message: 'Schedule deleted successfully' },
      { status: 200 }
    );
  } catch (error) {
    console.error('Error deleting schedule:', error);
    return NextResponse.json(
      { error: 'Failed to delete schedule' },
      { status: 500 }
    );
  }
}